package com.zaimokuza.cn.service.impl;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.zaimokuza.cn.entity.constants.SmsConstant;
import com.zaimokuza.cn.entity.enums.CustomizeExceptionEnum;
import com.zaimokuza.cn.service.SmsService;
import com.zaimokuza.cn.util.grace.GraceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author zaimokuza
 */
@Slf4j
@Service
public class SmsServiceImpl implements SmsService {

    @Resource(name = "smsClient")
    private Client client;

    /**
     * 获取验证码参数
     *
     * @param code 验证码
     * @return 格式化后的验证码参数
     */
    private static String getVerificationCodeParam(String code) {
        return String.format("{\"code\":\"%s\"}", code);
    }

    @Override
    public void sendVerificationCode(String phone, String code) {
        // 创建短信
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                // 手机号及验证码
                .setPhoneNumbers(phone).setTemplateParam(getVerificationCodeParam(code))
                // 短信签名及模板代码
                .setSignName(SmsConstant.SIGNATURE_NAME).setTemplateCode(SmsConstant.REGISTER_TEMPLATE_CODE);
        // 实例化返回对象
        SendSmsResponse sendSmsResponse = null;
        try {
            // 发送短信
            sendSmsResponse = client.sendSms(sendSmsRequest);
        } catch (Exception e) {
            // 捕获原始异常打印错误日志
            log.error("短信发送失败：" + e.getMessage(), e);
            // 抛出自定义异常
            GraceException.display(CustomizeExceptionEnum.SMS_SEND_ERROR);
        }
        // 检测返回状态码进行处理
        if (!SmsConstant.RESULT_OK.equals(sendSmsResponse.getBody().getCode())) {
            // 捕获原始异常打印错误日志
            log.error("短信发送失败:[{}][{}]", sendSmsResponse.getBody().getCode(), sendSmsResponse.getBody().getMessage());
            // 生成错误信息
            String errorMsg = String.format("短信发送失败[%s]！", sendSmsResponse.getBody().getCode());
            // 根据错误信息抛出自定义异常
            GraceException.display(CustomizeExceptionEnum.SMS_SEND_ERROR, errorMsg);
        }
    }
}
